package com.jack.lib.net.retry

import androidx.lifecycle.Lifecycle
import androidx.lifecycle.coroutineScope
import com.jack.lib.core.net.JBaseData
import com.jack.lib.net.JNet
import com.jack.lib.net.JNetParam
import kotlinx.coroutines.launch
import java.net.ConnectException
import java.net.NoRouteToHostException
import java.net.SocketTimeoutException
import java.net.UnknownHostException
import java.util.concurrent.ArrayBlockingQueue

/**
 * author : chong.huang
* create : 2/14/21
 * desc   :
 */
class AutoRetry : Retry {

    private val queue = ArrayBlockingQueue<JNetParam<*, *>>(100)

    override fun retry() {
        while (queue.isNotEmpty()) {
            val param = queue.poll()?: continue
            param.view.lifecycle().coroutineScope.launchWhenCreated { JNet.networkHandler(param) }
        }
    }

    override fun <T, J: JBaseData<T>> catchThrowableAdd(throwable: Throwable, param: JNetParam<T, J>) {
        if (!param.networkChangeAutoRetry) return
        when (throwable) {
            is UnknownHostException, is SocketTimeoutException, is NoRouteToHostException, is ConnectException -> {
                add(param)
            }
        }
    }

    override fun <T, J: JBaseData<T>> add(param: JNetParam<T, J>) {
        queue.offer(param.apply { cache.cancel() })
    }

}